package com.zl.iot.docking.util;

import com.aliyun.iot20180120.Client;
import com.aliyun.teaopenapi.models.Config;
import com.zl.iot.docking.exception.ZLExcep;
import com.zl.iot.docking.model.AliServerVO;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenzy
 * @since 2021-12-18
 **/
public interface AliUtil {
    Map<String,Client> clientMap = new HashMap<>();
//    StringMap<AsyncClient> clientMap2 = new StringMap<>();

    static Client getClient(AliServerVO aliServer) {
        var instanceId = getInstanceId(aliServer);
        if (clientMap.containsKey(instanceId)) {
            return clientMap.get(instanceId);
        }
        try {
            var client = new Client(new Config()
                    .setAccessKeyId(aliServer.getAccessKeyId())
                    .setAccessKeySecret(aliServer.getAccessSecret())
                    .setEndpoint(aliServer.getSysDomain()));
            clientMap.put(instanceId, client);
            return client;
        } catch (Exception e) {
            throw ZLExcep.error("阿里云通讯-获取客户端连接失败:", e);
        }
    }

  /*  static AsyncClient getClient2(AliServerVO aliServer) {
        var instanceId = getInstanceId(aliServer);
        if (clientMap2.containsKey(instanceId)) {
            return clientMap2.get(instanceId);
        }
        try {
            // Configure Credentials authentication information, including ak, secret, token
            var provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(aliServer.accessKeyId)
                    .accessKeySecret(aliServer.accessSecret)
                    //.securityToken("<your-token>") // use STS token
                    .build());
            // Configure the Client
            var client = AsyncClient.builder()
                    .region(aliServer.regionId) // Region ID
                    //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                    .credentialsProvider(provider)
                    //.serviceConfiguration(Configuration.create()) // Service-level configuration
                    // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride(aliServer.sysDomain)
                            //.setConnectTimeout(Duration.ofSeconds(30))
                    )
                    .build();
            clientMap2.add(instanceId, client);
            return client;
        } catch (Exception e) {
            throw PassExcep.error("阿里云通讯-获取异步客户端连接失败:", e);
        }
    }
*/
    static String getInstanceId(AliServerVO aliServer) {
        /*公共实例没有实例id*/
        return "test".equals(aliServer.getInstanceId()) ? "" : aliServer.getInstanceId();
    }
}
